﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace DailyApp.WPF.HttpClients
{
    /// <summary>
    /// 调用api的工具类
    /// </summary>
    internal class HttpRestClient
    {
        private readonly RestClient Client;//客户端
        /// <summary>
        /// 请求地址
        /// </summary>
        private readonly string baseUrl = "http://localhost:5179/api/";
        public HttpRestClient()
        {
            Client = new RestClient();
        }
        /// <summary>
        ///请求
        /// </summary>
        /// <param name="apiRequest">请求数据</param>
        /// <returns>接收的数据</returns>
        public ApiResponse Execute(ApiRequest apiRequest)
        {
            RestRequest restquest= new RestRequest(apiRequest.Method);//请求方式
            restquest.AddHeader("Content-Type",apiRequest.ContentType);//内容类型
            if(apiRequest.Parameters != null)//参数
            {
                restquest.AddParameter("param",JsonConvert.SerializeObject(apiRequest.Parameters),ParameterType.RequestBody);//序列号
            }
            Client.BaseUrl = new Uri(baseUrl+apiRequest.Route);
            var res=Client.Execute(restquest);
            if(res.StatusCode==System.Net.HttpStatusCode.OK)//判断请求是否成功
            {
                return JsonConvert.DeserializeObject<ApiResponse>(res.Content);//反序列化
            }
            else
            {
                return new ApiResponse { ResultCode = -99, Msg = "服务器崩溃了..." };
            }
        }
    }
}
